<template>
  <a-modal
    v-model:visible="visible"
    :title="titleObj[type]"
    width="600px"
    :after-close="afterClose"
    :destroy-on-close="true"
    :confirm-loading="loading"
    :mask-closable="false"
    :keyboard="false"
    @ok="handleSubmit"
  >
    <a-form
      ref="refForm"
      :model="formData"
      class="modal-main-content pt-8 pb-1"
      :label-col="{ style: { width: '120px' } }"
    >
      <a-form-item label="报表名称" name="templateName" :rules="{ required: true, message: '请输入报表名称' }">
        <a-input v-model:value.trim="formData.templateName" placeholder="请输入" :maxlength="50"></a-input>
      </a-form-item>
      <a-form-item
        :label="isTemp ? '模板文件' : '报表文件'"
        name="templateFileList"
        :rules="{ required: true, message: `请上传${isTemp ? '模板文件' : '报表文件'}` }"
      >
        <div class="pt-2">仅支持.docx格式文件</div>
        <MyUploadFile
          v-model:fileList="formData.templateFileList"
          :limit="1"
          :show-limit="false"
          btn-name="上传附件"
          :types="['docx']"
          :show-file-list="true"
        />
      </a-form-item>
      <a-form-item v-if="isInputFolder || isNeedSelectFolder" label="文件归档路径">
        <div v-if="isNeedSelectFolder">
          <a-button type="primary" @click="handleSelect">选择</a-button>
          <div class="mt-2">{{ formData.archiveFolderName }}</div>
        </div>
        <a-input
          v-else
          v-model:value="formData.archiveFolderName"
          :maxlength="200"
          placeholder="请输入归档路径"
        ></a-input>
      </a-form-item>
    </a-form>
  </a-modal>

  <SelectAchiveFolder
    ref="refSelectFolder"
    title-str="选择归档路径"
    :tree-data-list="treeDataList"
    @onGetArchiveFolderId="getArchiveFolderId"
  ></SelectAchiveFolder>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { copyObj } from '@@/utils/index'
import MyUploadFile from '@@/components/MyUploadFile.vue'
import { getCtmsArchiveFolder, getArchiveFolderByProjectType } from '@@/api/project/documentManage'
import { PTgetById } from '@@/api/progresstemplate'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const props = withDefaults(
  defineProps<{
    updateFn: any
    addFn: any
    taskId: string
    isNeedSelectFolder: boolean
    speedId?: string | null | undefined
    isByProjectType?: any
    projectType?: any
    isInputFolder?: boolean
    isTemp?: boolean
  }>(),
  {
    isNeedSelectFolder: true,
    speedId: '',
    isByProjectType: false,
    projectType: ''
  }
)
const visible = ref<boolean>(false)
const emits = defineEmits(['submit', 'reload'])
const titleObj = {
  1: '新增报表',
  2: '编辑',
  3: '编辑'
}
const type = ref<number>(1)
const receiptTemplateId = ref<string>()
const formData = ref<any>({})
// _type:1-使用空白模板，2-选择模板，3-修改
const show = (_type, data?) => {
  if (props.isNeedSelectFolder) {
    if (route.path === '/sop/progressTemplate/index' || route.path === '/configure/progress/index') {
      // sop-进度
      getSpeedDeital()
    } else if (props.isByProjectType) {
      getTreeData()
    } else {
      // 项目-进度
      reloadTreeData()
    }
  }
  type.value = _type
  if (_type !== 1) {
    formData.value = copyObj(data)
    formData.value.templateFileList = [
      {
        uid: data.fileId || data.templateFileId,
        name: data.fileName || data.templateFileName
      }
    ]
    formData.value.archiveFolderName = data.archiveFolderPath || data.archiveFolderName || ''
  }
  visible.value = true
}

const treeDataList = ref<any>([])
// 获取树数据
const reloadTreeData = () => {
  getCtmsArchiveFolder({ projectId: sessionStorage.getItem('__projectId') })
    .then((res) => {
      treeDataList.value = res ? [res] : []
      addFolderKey(treeDataList.value, 'archiveFolderId')
    })
    .catch(() => {})
}
const refSelectFolder = ref()

const handleSelect = () => {
  if (!treeDataList.value || !treeDataList.value.length) {
    return message.warning('请先选择文件夹目录')
  }
  refSelectFolder.value.show(formData.value)
}

// 添加树组件所需的key
const addFolderKey = (list, key) => {
  list.forEach((item) => {
    if (item[key]) {
      item.folderKey = item[key]
    }
    if (item.children && item.children.length) {
      addFolderKey(item.children, key)
    }
  })
}

// sop获取项目文件夹目录模板的目录
const getSpeedDeital = () => {
  PTgetById({
    speedId: props.speedId
  }).then((res) => {
    treeDataList.value = res.folder ? [res.folder] : []
    addFolderKey(treeDataList.value, 'speedFolderId')
  })
}

const getTreeData = () => {
  getArchiveFolderByProjectType({
    projectType: props.projectType
  }).then((res) => {
    treeDataList.value = res.folder ? [res.folder] : []
    addFolderKey(treeDataList.value, 'projectFolderId')
  })
}
// 获取归档文档id
const getArchiveFolderId = ({ checkedKey, pathName }) => {
  formData.value.speedFolderId = checkedKey
  formData.value.archiveFolderId = checkedKey
  formData.value.archiveFolderName = pathName
}

const afterClose = () => {
  formData.value = {}
  receiptTemplateId.value = ''
}
const refForm = ref()
const loading = ref<boolean>(false)
const handleSubmit = async () => {
  const valid = await refForm.value.validate()
  if (valid) {
    loading.value = true
    let params = {
      archiveFolderId: formData.value.archiveFolderId || formData.value.speedFolderId,
      archiveFolderName: formData.value.archiveFolderName,
      templateName: formData.value.templateName,
      templateFileId: formData.value.templateFileList[0].uid,
      templateFileName: formData.value.templateFileList[0].name
    }
    if (type.value === 3) {
      Object.assign(params, {
        receiptId: formData.value.receiptId
      })
      // 编辑
      props
        .updateFn(params)
        .then(() => {
          emits('reload')
          visible.value = false
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      params = Object.assign(params, {
        businessId: props.taskId,
        projectId: sessionStorage.getItem('__projectId') || ''
      })
      // 新增
      props
        .addFn(params)
        .then(() => {
          emits('reload')
          visible.value = false
        })
        .finally(() => {
          loading.value = false
        })
    }
  }
}
defineExpose({
  show
})
</script>
